import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { CreateUserDto, UserServiceProxy, RoleDto } from '@shared/service-proxies/service-proxies';
import { ModalComponentBase } from '@shared/component-base';
import { OrganizationUnitsServiceProxy } from 'services/organizationunits/organizationunits.service';
import { NzFormatEmitEvent, NzTreeNode } from 'ng-zorro-antd';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styles: [],
  providers: [OrganizationUnitsServiceProxy]
})
export class CreateUserComponent extends ModalComponentBase implements OnInit {
  @ViewChild('treeCom') treeCom;
  @ViewChild('validateForm') validateForm: FormGroup;

  user: CreateUserDto = new CreateUserDto();
  roles: RoleDto[] = null;
  roleList = [];
  confirmPasswordInput: string = '';
  //组织单位树
  searchValue;
  nodes = [];

  constructor(injector: Injector, private _userService: UserServiceProxy, private organizationunitsService: OrganizationUnitsServiceProxy) {
    super(injector);
  }

  ngOnInit() {
    this.fetchData();
    this.user.isActive = true;
  }



  fetchData(): void {
    //获取角色
    this._userService.getRoles()
      .subscribe((result) => {
        this.roles = result.items;
        //获取组织单位
        this.organizationunitsService.GetTreesAsync().subscribe((data) => {
          this.nodes = this.handle(data);
        });
        this.roles.forEach((item) => {
          this.roleList.push({
            label: item.displayName, value: item.name, checked: true
          });
        });
      });
  }
  //递归处理组织单位数据,默认全展开
  handle(data: NzTreeNode[]): NzTreeNode[] {
    data.forEach((item) => {
      item.isExpanded = true;
      let tempTitle = item.title;
      item.title = tempTitle.substring(0, tempTitle.indexOf("（"));
      if (!item.isLeaf) {
        this.handle(item.children);
      }
    })
    return data;
  }
  nzEvent(event: NzFormatEmitEvent): void {

    console.log(event, this.treeCom.getMatchedNodeList().map(v => v.title));
  }

  save(): void {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) {
      return;
    }
    let tmpRoleNames = [];
    this.roleList.forEach((item) => {
      if (item.checked) {
        tmpRoleNames.push(item.value);
      }
    });
    this.user.roleNames = tmpRoleNames;
    this.user.organizationUnitIds = this.treeCom.getCheckedNodeList().map(v => v.key);
    if (this.user.organizationUnitIds == null || this.user.organizationUnitIds.length <= 0) {
      this.message.error('组织单位必选');
      return
    }
    this.user.surname = this.user.name;

    this._userService.create(this.user)
      .finally(() => { this.saving = false; })
      .subscribe(() => {
        this.notify.success('保存成功');
        this.success();
      });
  }


}
